<?php
// +----------------------------------------------------------------------
// | najing [ 通用后台管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.najingquan.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: cou
// +----------------------------------------------------------------------

namespace app\common\model;


use app\common\model\User as UserModel;

class UserLog extends Common
{

    const USER_LOGIN = 1;     //登录
    const USER_LOGOUT = 2;    //退出
    const USER_REG = 3;    //注册
    const USER_EDIT = 4;    //用户编辑信息

    /**
     * 总后台的登陆记录
     * @author cou
     */
    public function getList( $user_id = '', $limit = 5 )
    {
        $where = [];
        if($user_id){
            $where[] = ['user_id','=',$user_id];
        }
        $where[] = ['state','=',1];
        $data = $this->where($where)
            ->order('ctime DESC')
            ->paginate($limit);

        $data = $this->tableFormat($data->getCollection());

        foreach( $data as $key => $val )
        {
            $userModel              = new UserModel();
            $userInfo               = $userModel->field('id,username,nickname,mobile')->where(['id' => $val['user_id']])->select();
            $data[$key]['username'] = $userInfo[0]['mobile'];
        }

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = count($data);
        $re['data'] = $data;

        return $re;

    }

    /**
     * where查询条件
     * @author cou
     */
    protected function tableWhere($post)
    {
        $where = [];
        if(isset($post['user_id']) && $post['user_id'] != ""){
            $where[] = ['user_id', '=', $post['user_id']];
        }
        if (isset($post['id']) && $post['id'] != "") {
            $where[] = ['id', '=', $post['id']];
        }
        if(!empty($post['date']))
        {
            $date_string = $post['date'];
            $date_array = explode(' 到 ', $date_string);
            $sdate = strtotime($date_array[0].' 00:00:00');
            $edate = strtotime($date_array[1].' 23:59:59');
            $where[] = array('ctime', ['>=', $sdate], ['<', $edate], 'and');
        }
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = "ctime desc";
        return $result;
    }
    /**
     * 根据查询结果，格式化数据
     * @author cou
     * @param $list  array格式的collection
     * @return mixed
     */
    protected function tableFormat($list)
    {
        foreach($list as $k => $v) {
            $list[$k]['state'] = config('params.user')['state'][$v['state']];
            $list[$k]['ctime'] = getTime($v['ctime']);
        }
        return $list;
    }


    /**
     *  添加日志
     * @author cou
     * @param $user_id
     * @param string $state
     */
    public function setLog( $user_id,$state,$data = [] )
    {

        $data = [
            'user_id' => $user_id,
            'state' => $state,
            'ctime' => time(),
            'params' => json_encode($data),
            'ip' => get_client_ip(0,true)
        ];
        $this->save($data);
    }

    /**
     * 按天统计会员的数据
     * @author cou
     */
    public function statistics($day,$state)
    {
        $where['state'] = $state;
        $field = 'state,DATE_FORMAT(from_unixtime(ctime),"%Y-%m-%d") as day, count(*) as nums';

        $res = $this->field($field)->where($where)->where("TIMESTAMPDIFF(DAY,from_unixtime(ctime),now()) <7")->group('DATE_FORMAT(from_unixtime(ctime),"%Y-%m-%d")')->select();
        $data = get_lately_days($day, $res);
        return ['day' => $data['day'], 'data' => $data['data']];
    }

    /**
     * 返回layui的table所需要的格式
     * @author cou
     */
    public function tableDatas($post, $isPage = true)
    {
        if (isset($post['limit'])) {
            $limit = $post['limit'];
        } else {
            $limit = config('paginate.list_rows');
        }
        $tableWhere = $this->tableWheres($post);
        $list       = [];
        if ($isPage) {
            $list        = $this->with('grade')->field($tableWhere['field'])->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);
            $data        = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
            $re['count'] = $list->total();
        } else {
            $list = $this->field($tableWhere['field'])->where($tableWhere['where'])->order($tableWhere['order'])->select();
            if (!$list->isEmpty()) {
                $data = $this->tableFormat($list->toArray());
            }
            $re['count'] = count($list);
        }
        $userModel = new User();
        foreach ($data as &$v)
        {
            $userInfo = $userModel->field('id,username,nickname,mobile')->where(['id' => $v['user_id']])->select();
            $v['username'] = $userInfo[0]['mobile'];
        }
        $re['code'] = 0;
        $re['msg']  = '';

        $re['data'] = $data;

        return $re;
    }

    /**
     * where查询条件
     * @author cou
     */
    protected function tableWheres($post)
    {
        $where = [];
        if (isset($post['id']) && $post['id'] != "") {
            $where[] = ['id', 'in', $post['id']];
        }
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = "id desc";
        return $result;
    }

}